﻿<?php 
	if (intval($_GET['install'])) 
	{
		$n = intval($_GET['n']);
		$arr = array();

		$dbHost = trim($_POST['dbHost']);
		$dbPort = trim($_POST['dbPort']);
		$dbName = trim($_POST['dbName']);
		$dbHost = empty($dbPort) || $dbPort == 3306 ? $dbHost : $dbHost . ':' . $dbPort;
		$dbUser = trim($_POST['dbUser']);
		$dbPwd = trim($_POST['dbPwd']);
		$insql = isset($_POST['insql'])?trim($_POST['insql'])+0:0;
		$urlMod = trim($_POST['urlMod'])+0;
		if($urlMod<=1)$urlMod=1;
		if($urlMod>=3)$urlMod=3;
		$dbPrefix = 'bbcms_';

		if($insql==1)
		{
			$conn = @ mysql_connect($dbHost, $dbUser, $dbPwd);
			if (!$conn) 
			{
				$arr['msg'] = "连接数据库失败!";
				echo json_encode($arr);
				exit;
			}
			mysql_query("SET NAMES 'utf8'"); //,character_set_client=binary,sql_mode='';
			$version = mysql_get_server_info($conn);
			if ($version < 4.1) 
			{
				$arr['msg'] = '数据库版本太低!';
				echo json_encode($arr);
				exit;
			}

			if (!mysql_select_db($dbName, $conn))
			{
				//创建数据时同时设置编码
				if (!mysql_query("CREATE DATABASE IF NOT EXISTS `" . $dbName . "` DEFAULT CHARACTER SET utf8;", $conn)) {
					$arr['msg'] = '数据库 ' . $dbName . ' 不存在，也没权限创建新的数据库！';
					echo json_encode($arr);
					exit;
				}
				if (empty($n)) {
					$arr['n'] = 1;
					$arr['msg'] = "成功创建数据库:{$dbName}<br>";
					echo json_encode($arr);
					exit;
				}
				mysql_select_db($dbName, $conn);
			}

			//读取数据文件
			$sqldata = file_get_contents(SITEDIR . 'install/' . $sqlFile);
			$sqlFormat = sql_split($sqldata, $dbPrefix);

			/**
			  执行SQL语句
			 */
			$counts = count($sqlFormat);

			for ($i = $n; $i < $counts; $i++) 
			{
				$sql = trim($sqlFormat[$i]);

				if (strstr($sql, 'CREATE TABLE')) 
				{
					preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
					mysql_query("DROP TABLE IF EXISTS `$matches[1]");
					$ret = mysql_query($sql);
					if ($ret) 
					{
						$message = '<font color="gree">成功创建数据表：' . $matches[1] . ' 即将进行信息导入，时间会比较久，请耐心等候... </font><br />';
					} else 
					{
						$message = '<font  color="red">创建数据表失败：' . $matches[1] . ' </font><br />';
					}
					$i++;
					$arr = array('n' => $i, 'msg' => $message);
					echo json_encode($arr);
					exit;
				} else 
				{
					$ret = mysql_query($sql);
					$message = '';
					$arr = array('n' => $i, 'msg' => $message);
					//echo json_encode($arr); exit;
				}
			}

			if ($i == 999999)
				exit;
		}
	   
		//读取配置文件，并替换真实配置数据
		$strConfig = file_get_contents(SITEDIR . 'install/' . $configFile);
		$strConfig = str_replace('#URL_MODEL#', $urlMod, $strConfig);
		$strConfig = str_replace('#DB_HOST#', $dbHost, $strConfig);
		$strConfig = str_replace('#DB_NAME#', $dbName, $strConfig);
		$strConfig = str_replace('#DB_USER#', $dbUser, $strConfig);
		$strConfig = str_replace('#DB_PWD#', $dbPwd, $strConfig);
		$strConfig = str_replace('#DB_PORT#', $dbPort, $strConfig);
		$strConfig = str_replace('#DB_PREFIX#', $dbPrefix, $strConfig);
		file_put_contents(SITEDIR . 'App/Conf/config.php', $strConfig);
		file_put_contents(SITEDIR . 'index.php', $strIndex);
		deldir(SITEDIR . 'App/Runtime');
		$message = '成功写入配置文件<br>安装完成．';
		$arr = array('n' => 999999, 'msg' => $message);
		echo json_encode($arr);
		exit;
	}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title><?php echo $steps[$step];?>东丘CMS > 安装向导</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="./js/jquery.min.js" language="javascript" type="text/javascript"></script>
        <script src="./js/jquery.form.js" language="javascript" type="text/javascript"></script>
        <script src="./js/jquery.validate.js" language="javascript" type="text/javascript"></script>
        <link href="./css/style.css" rel="stylesheet" type="text/css" />
		
		<script language="javascript" type="text/javascript">
			<!--
			$(document).ready(function(){
				$(".table tr").each(function(){ $(this).children("td").eq(0).addClass("on");});
				$("input[type='text']").addClass("input_blur").mouseover(function(){ $(this).addClass("input_focus");}).mouseout(function(){$(this).removeClass("input_focus");});
				$(".table tr").mouseover(function(){ $(this).addClass("mouseover");}).mouseout(function(){$(this).removeClass("mouseover");	});
			});
			-->
		</script>
		
		<script language="javascript" type="text/javascript">
			var n=0;
			var data = <?php echo json_encode($_POST);?>;
			$.ajaxSetup ({ cache: false });
			function reloads(n) {
				var url =  "./index.php?step=4&install=1&n="+n;
				$.ajax({
					type: "POST",		
					url: url,
					data: data,
					dataType: 'json',
					beforeSend:function(){
					},
					success: function(msg){
						if(msg.n=='999999'){
							$('#dosubmit').attr("disabled",false);
							$('#dosubmit').removeAttr("disabled");				
							$('#dosubmit').removeClass("nonext");
							setTimeout('gonext()',2000);
						}
						if(msg.n){
							$('#setupinfo').append(msg.msg);	
							reloads(msg.n);	
						}else{
							//alert('指定的数据库不存在，系统也无法创建，请先通过其他方式建立好数据库！');
							alert(msg.msg);
						}			 
					}
				});
			}
			function gonext(){
				window.location.href='index.php?step=5';
			}
			$(document).ready(function(){
				reloads(n);
			})
		</script>

    </head>
    <body>
        <div class="main">
            <h5>欢迎使用东丘贸易管理系统</h5>

            <div class="title">
				<ul>
                    <?php  foreach($steps as $key=>$res){ ?>
                    <li <?php if($step==$key):?> class="on"<?php endif;?> ><?php echo $res?></li>
                    <?php } ?>
                </ul>
			</div>

            <div class="box">
				<div class="b1">
					<div class="right">
						<h2>Step <?php echo $step;?> of 5 </h2>

						<h1>正在安装</h1>

						<div id="setupinfo">正在开始安装...<br><font color="#FF0000">如果长时间卡住，请刷新本页面！</font><br></div>

						<div class="butbox">
							<input type="button" class="inputButton" value=" 上一步 " onclick="window.location.href='index.php?step=3';" style="margin-right:20px" />
							<input name="dosubmit" type="submit" class="inputButton nonext" id="dosubmit" value=" 下一步 " disabled  />
						</div>
					</div>
				</div>
			</div>
			<div class="power">Powered by <a href="#" target="_blank">大连东丘贸易有限公司</a> 
			</div>
		</div>
	</body>
</html>
